import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:wechat_kit/wechat_kit.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/pay/ali_pay_utils.dart';
import 'package:tracker/common/pay/model/order_info_req.dart';
import 'package:tracker/common/pay/wxpay_utils.dart';
import 'package:tracker/common/widget/pay_dialog_widget.dart';
import 'package:tracker/pages/home/flowcard/model/card_packages_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/num_utils.dart';
import 'package:material_dialogs/material_dialogs.dart';
import 'package:tracker/utils/toast_utils.dart';

import '../../../../common/constants/app_constants.dart';

/// 套餐类型枚举
enum PackageType {
  /// 流量叠加包
  additionalPackage,

  /// 主套餐
  mainPackage,
}

/// 充值套餐页面
class ChargePage extends ConsumerStatefulWidget {
  final String iccid;

  const ChargePage({super.key,required this.iccid});

  @override
  ConsumerState<ChargePage> createState() => _ChargePageState();
}

class _ChargePageState extends ConsumerState<ChargePage> {

  bool showLoading = true;
  List<PackageMenuInfo> normalList = <PackageMenuInfo>[];

  List<PackageMenuInfo> yearList = <PackageMenuInfo>[];
  List<Widget> yearListItemArr = <Widget>[];

  PayDialogWidget payDialogWidget = PayDialogWidget();
  final alipayUtils = AliPayUtils();
  final wxpayUtils = WxpayUtils();
  PackageMenuInfo choosePackageMenuInfo = PackageMenuInfo();
  _showLoading() {
    return Center(
      child: CircularProgressIndicator(
        color: AppTheme.themeConfig.primaryColor,
      ),
    );
  }

  _fetchCardPackages() async {
    // final deviceInfo = ref.watch(deviceInfoProvider);
    // final queryParams = {
    //   'iccid': deviceInfo.iccid,
    //   'imei': deviceInfo.imei,
    //   // 'iccid': '89860479042070143369',
    //   // 'imei': '58058888888',
    // };
    // final res = await get<CardPackagesResp, CardPackagesResp>('',
    //     queryParameters: queryParams, decodeType: CardPackagesResp());
    // setState(() {
    //   showLoading = false;
    // });
    // res.when(success: (CardPackagesResp resp) {
    //   if (resp.code == 200) {
    //     setState(() {
    //       showLoading = false;
    //       cardPackagesData = resp.data!;
    //     });
    //   }
    // }, failure: (String msg, int code) {
    //   setState(() {
    //     showLoading = false;
    //   });
    // });

    var loadingIndex = 0;


    final queryParams = {
      'type': "1",//_searchKeyword,
    };
    final res = await get<PackageMenuInfoResp, PackageMenuInfoResp>('$newBaseULr/sim/package/list',
        queryParameters: queryParams, decodeType: PackageMenuInfoResp());
    res.when(success: (PackageMenuInfoResp resp) {
      loadingIndex ++;
      XLogger.error(resp.code);

      if (resp.code == 200) {
        if (loadingIndex == 2) {
          showLoading = false;
        }

        if (resp.data != null) {
          setState(() {
            normalList = resp.data!;
          });
        }

      } else {
        ToastUtils.showToast(resp.msg ?? '获取设备列表失败');
        XLogger.error('获取设备列表失败 ');

      }
      setState(() {
        if (loadingIndex == 2) {
          showLoading = false;
        }
      });
    }, failure: (String msg, int code) {
      XLogger.error('获取设备列表失败 ');

    });



    final queryYearParams = {
      'type': "2",//_searchKeyword,
    };
    final resYear = await get<PackageMenuInfoResp, PackageMenuInfoResp>('$newBaseULr/sim/package/list',
        queryParameters: queryYearParams, decodeType: PackageMenuInfoResp());
    resYear.when(success: (PackageMenuInfoResp resp) {
      loadingIndex ++;

      if (resp.code == 200) {
        if (loadingIndex == 2) {
          showLoading = false;
        }

        if (resp.data != null) {
          setState(() {
            yearList = resp.data!;

          });
        }
      } else {
        ToastUtils.showToast(resp.msg ?? '获取设备列表失败');
        XLogger.error('获取设备列表失败 ');

      }
      setState(() {
        if (loadingIndex == 2) {
          showLoading = false;
        }
      });
    }, failure: (String msg, int code) {
      XLogger.error('获取设备列表失败 code: $code msg: $msg');
    });

  }

  List<Widget> packageItemsWidget(PackageType type) {
    // List<Widget> ItemArr = <Widget>[];

    if (type == PackageType.additionalPackage) {
      return normalList.map((package) {
        return _buildPackageItem((package.title ?? ""),package.price.toString(),type,package);
      }).toList();


    }else {
      return yearList.map((package) {
        return _buildPackageItem(package.title ?? "",package.price.toString(),type,package);
      }).toList();
    }


  }

  Widget _buildBodyView() {
    final screenWidth = MediaQuery.of(context).size.width;

    return SingleChildScrollView(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 流量叠加包模块
          _buildPackageSection(
            title: '流量叠加包',
            subtitle: '当月有效',
            screenWidth: screenWidth,
            packages: packageItemsWidget(PackageType.additionalPackage),
          ),
          const SizedBox(height: 20),
          // 年卡套餐模块
          _buildPackageSection(
            title: '年卡套餐',
            subtitle: '有限期一年',
            screenWidth: screenWidth,
            packages: packageItemsWidget(PackageType.mainPackage),
          ),
          const SizedBox(height: 20),
          // 温馨提示
          const Text(
            '温馨提示：',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          const Text(
            '订购即使生效，不限订购次数，主套餐到期流量清零',
            style: TextStyle(fontSize: 14),
          ),
          const Text(
            '流量卡充值可能会延迟到账，若长时间未到账，',
            style: TextStyle(fontSize: 14),
          ),
          RichText(
            text: const TextSpan(
              text: '请联系客服处理，对订单有任何疑问，请联系',
              style: TextStyle(fontSize: 14, color: Colors.black),
              children: [
                TextSpan(
                  text: '在线客服',
                  style: TextStyle(color: Colors.black),
                ),
              ],
            ),
          ),
          const SizedBox(height: 40),
          // 底部充值按钮
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () {
                // 这里可以添加充值按钮的点击逻辑
                _showPackageInfoDialog(choosePackageMenuInfo, PackageType.mainPackage);

              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: const Text(
                '充值',
              ),
            ),
          ),
        ],
      ),
      // ),
    );
  }

  // 构建套餐模块的方法
  // 构建套餐模块的方法
  Widget _buildPackageSection({
    required String title,
    required String subtitle,
    required double screenWidth,
    required List<Widget> packages,
  }) {
    // 计算每个套餐项的宽度，确保每行显示3个
    // 减去左右内边距和间距
    final itemWidth = (screenWidth - 16 * 2 - 16 * 2) / 3;

    return Container(
      padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: const [
          BoxShadow(
            color: Colors.black12,
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text(
                title,
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(
                subtitle,
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 14,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Wrap(
            // 水平间距
            spacing: 8,
            // 垂直间距
            runSpacing: 16,
            children: packages.map((package) {
              // 设置每个套餐项的固定宽度
              return SizedBox(
                width: itemWidth,
                child: package,
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  // 构建单个套餐项的方法
  Widget _buildPackageItem(String name, String price, PackageType packageType,PackageMenuInfo model) {
    return GestureDetector(
        onTap: () {
      setState(() {
        choosePackageMenuInfo = model;
      });
    },
    child: Container(
      width: 120,
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
      decoration: BoxDecoration(
        border: Border.all(color: packageType == PackageType.additionalPackage
            ? choosePackageMenuInfo.title == name
            ?  ColorUtils.hexToColor('#009FE9') : ColorUtils.hexToColor("#B5D6FF")
            : choosePackageMenuInfo.title == name
            ? ColorUtils.hexToColor("#F93A4A") : ColorUtils.hexToColor("#FFE3E5"),),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          Text(
            name,
            style: TextStyle(
              color: packageType == PackageType.additionalPackage
                    ? choosePackageMenuInfo.title == name
                      ?  ColorUtils.hexToColor('#009FE9') : ColorUtils.hexToColor("#B5D6FF")
                    : choosePackageMenuInfo.title == name
                      ? ColorUtils.hexToColor("#F93A4A") : ColorUtils.hexToColor("#FFE3E5"),
              fontSize: 13,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            price,
            style: TextStyle(
              color: packageType == PackageType.additionalPackage
                  ? choosePackageMenuInfo.title == name
                    ? ColorUtil.hexToColor("#009FE9") : ColorUtil.hexToColor("#B5D6FF")
                  : choosePackageMenuInfo.title == name
                    ? ColorUtil.hexToColor("#009FE9") : ColorUtil.hexToColor("#B5D6FF"),
              fontSize: 14,
            ),
          ),
        ],
      ),
    ),
    );
  }

  // 删除
  // Widget _buildAdditionalPackageView() {
  //   return Container(
  //     width: MediaQuery.of(context).size.width,
  //     margin: const EdgeInsets.only(top: 20, left: 20, right: 20),
  //     padding: const EdgeInsets.all(12),
  //     decoration: BoxDecoration(
  //       color: Colors.white,
  //       borderRadius: BorderRadius.circular(10),
  //     ),
  //     child: Column(
  //       children: [
  //         // 标题
  //         const Row(
  //           children: [
  //             Text(
  //               '流量叠加包',
  //               style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
  //             ),
  //           ],
  //         ),
  //         const SizedBox(
  //           height: 12,
  //         ),
  //         GridView.builder(
  //           shrinkWrap: true,
  //           physics: const NeverScrollableScrollPhysics(),
  //           itemCount: cardPackagesData.additionalPackageInfo?.length ?? 0,
  //           gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
  //             crossAxisCount: 3,
  //             mainAxisSpacing: 20,
  //             crossAxisSpacing: 20,
  //             childAspectRatio: 1.2,
  //           ),
  //           itemBuilder: (BuildContext context, int index) {
  //             return _buildAdditionalPackageItemView(index);
  //           },
  //         ),
  //       ],
  //     ),
  //   );
  // }
  //
  // _buildAdditionalPackageItemView(int index) {
  //   final packageInfo = cardPackagesData.additionalPackageInfo![index];
  //   final money = NumUtils.formatNum(packageInfo.price);
  //   final consumption = NumUtils.formatNum(packageInfo.consumption);
  //   return GestureDetector(
  //     onTap: () {
  //       _showPackageInfoDialog(packageInfo, PackageType.additionalPackage);
  //     },
  //     child: Container(
  //       padding: const EdgeInsets.all(4),
  //       decoration: BoxDecoration(
  //         color: ColorUtils.hexToColor('#deebff'),
  //         borderRadius: BorderRadius.circular(10),
  //       ),
  //       child: Column(
  //         mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  //         children: [
  //           Text(
  //             '${consumption}M/${packageInfo.packageName}',
  //             style: TextStyle(fontSize: 14, color: AppTheme.themeConfig.primaryColor),
  //             maxLines: 1,
  //           ),
  //           Text(
  //             '￥${money}',
  //             style: TextStyle(fontSize: 17, color: AppTheme.themeConfig.primaryColor, fontWeight: FontWeight.bold),
  //             maxLines: 1,
  //           ),
  //         ],
  //       ),
  //     ),
  //   );
  // }

  // Widget _buildMainPackageView() {
  //   return Container(
  //     width: MediaQuery.of(context).size.width,
  //     margin: const EdgeInsets.only(top: 20, left: 20, right: 20),
  //     padding: const EdgeInsets.all(12),
  //     decoration: BoxDecoration(
  //       color: Colors.white,
  //       borderRadius: BorderRadius.circular(10),
  //     ),
  //     child: Column(
  //       children: [
  //         // 标题
  //         const Row(
  //           children: [
  //             Text(
  //               '主套餐',
  //               style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
  //             ),
  //           ],
  //         ),
  //         const SizedBox(
  //           height: 12,
  //         ),
  //         GridView.builder(
  //           shrinkWrap: true,
  //           physics: const NeverScrollableScrollPhysics(),
  //           itemCount: cardPackagesData.mainPackageInfo == null ? 0 : 1,
  //           gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
  //             crossAxisCount: 3,
  //             mainAxisSpacing: 20,
  //             crossAxisSpacing: 20,
  //             childAspectRatio: 1.2,
  //           ),
  //           itemBuilder: (BuildContext context, int index) {
  //             return _buildMainPackageItemView(index);
  //           },
  //         ),
  //       ],
  //     ),
  //   );
  // }
  //
  // Widget _buildMainPackageItemView(int index) {
  //   final mainPackageInfo = cardPackagesData.mainPackageInfo!;
  //   final money = NumUtils.formatNum(mainPackageInfo.price);
  //   final consumption = NumUtils.formatNum(mainPackageInfo.consumption);
  //   return GestureDetector(
  //     onTap: () {
  //       _showPackageInfoDialog(mainPackageInfo, PackageType.mainPackage);
  //     },
  //     child: Container(
  //       padding: const EdgeInsets.all(4),
  //       decoration: BoxDecoration(
  //         color: ColorUtils.hexToColor('#deebff'),
  //         borderRadius: BorderRadius.circular(10),
  //       ),
  //       child: Column(
  //         mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  //         children: [
  //           Text(
  //             '${consumption}M/${mainPackageInfo.packageName}',
  //             style: TextStyle(fontSize: 14, color: AppTheme.themeConfig.primaryColor),
  //             maxLines: 1,
  //           ),
  //           Text(
  //             '￥${money}',
  //             style: TextStyle(fontSize: 17, color: AppTheme.themeConfig.primaryColor, fontWeight: FontWeight.bold),
  //             maxLines: 1,
  //           ),
  //         ],
  //       ),
  //     ),
  //   );
  // }

  /// 弹窗显示套餐信息
  _showPackageInfoDialog(PackageMenuInfo packageInfo, PackageType packageType) {
    final consumption = NumUtils.formatNum(packageInfo.number);
    final packageName = packageInfo.title;
    final price = NumUtils.formatNum(packageInfo.price);
    Dialogs.bottomMaterialDialog(
        color: Colors.white,
        context: context,
        customView: StatefulBuilder(builder: (context, setState) {
          return Container(
            width: double.infinity,
            padding: const EdgeInsets.only(left: 20, right: 20, top: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  packageName ?? '',
                  style: const TextStyle(
                      fontSize: 16, fontWeight: FontWeight.bold),
                ),
                const SizedBox(
                  height: 20,
                ),
                Text(
                  '数量：${consumption}M',
                  style: TextStyle(
                      fontSize: 16, color: AppTheme.themeConfig.infoTextColor),
                ),
                const SizedBox(
                  height: 8,
                ),
                Text(
                  '生效时间：立即生效',
                  style: TextStyle(
                      fontSize: 16, color: AppTheme.themeConfig.infoTextColor),
                ),
                // 虚线
                Divider(
                  height: 28,
                  thickness: 1,
                  color: ColorUtils.hexToColor('#e5e5e5'),
                ),
                Text(
                  '充值号码：',
                    // ${cardPackagesData.cardNo}',
                  style: TextStyle(
                      fontSize: 16, color: AppTheme.themeConfig.infoTextColor),
                ),
                const SizedBox(
                  height: 8,
                ),
                Text(
                  '价格：${price}',
                  style: TextStyle(
                      fontSize: 16, color: AppTheme.themeConfig.infoTextColor),
                ),
              ],
            ),
          );
        }),
        actions: [
          TextButton(
            onPressed: () {
              _showPayDialog(packageInfo, packageType);
            },
            style: ButtonStyle(
              backgroundColor:
                  MaterialStateProperty.all(AppTheme.themeConfig.primaryColor),
              shape: MaterialStateProperty.all(RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20))),
              minimumSize:
                  MaterialStateProperty.all(const Size(double.infinity, 40)),
            ),
            child: const Text(
              '订购',
              style: TextStyle(fontSize: 16, color: Colors.white),
            ),
          )
        ]);
  }

  /// 选择支付方式
  _showPayDialog(PackageMenuInfo packageInfo, PackageType packageType) {
    payDialogWidget.showPayDialog(context, '${packageInfo.price}',
        onConfirm: (payType) {
          print(payType);
          if (payType == PayType.alipay) {
            alipayUtils.createChargeSIMCard(packageInfo.packageId, widget.iccid);
          }else {
            wxpayUtils.createChargeSIMCard(packageInfo.packageId, widget.iccid);

          }
    //

    });
  }

  /// 点击订购
  _doBuy(PackageMenuInfo packageInfo, PackageType packageType, PayType payType) {
    // packageInfo.packageType = packageType == PackageType.mainPackage ? 1 : 2;
    // final deviceInfo = ref.watch(deviceInfoProvider);
    // // 支付方式
    // final payAccount = PayUtils.getPayAccount(payType);
    // final payTypeParams = PayUtils.getPayType(payType);
    // final orderInfoReq = OrderInfoReq(
    //   imei: deviceInfo.imei,
    //   payType: payTypeParams,
    //   payAccount: payAccount,
    //   orderType: 1,
    //   flowPackage: packageInfo,
    // );
    // XLogger.debug('orderInfoReq: ${orderInfoReq.toJson()}');
    // if (payType == PayType.alipay) {
    //   alipayUtils.createOrder(orderInfoReq);
    // } else if (payType == PayType.wechat) {
    //   wxpayUtils.createOrder(
    //       deviceInfo.imei ?? "", packageInfo.packageId?.toInt() ?? 0);
    // } else if (payType == PayType.wechatUnion) {
    //   wxpayUtils.createMiniAppOrder(orderInfoReq);
    // }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _fetchCardPackages();
    });
    // 支付宝支付监听
    alipayUtils.listenPay((resp) {
      context.pop();
      XLogger.info('流量卡支付结果：${resp.resultStatus}');
      if (resp.isSuccessful) {
        // 支付成功
        ToastUtils.showSimpleDialog(context,
            title: '提示',
            content: '套餐购买成功',
            confirmTitle: '好的', confirmCallback: () {
          // 关闭当前页面
          context.pop();
        });
      } else {
        // 支付失败
        ToastUtils.showToast('支付失败');
      }
    });
    // 微信支付监听
    // wxpayUtils.registerWechatResp((resp) {
    //   context.pop();
    //   XLogger.info('流量卡支付结果：${resp}');
    //   if (resp.isSuccessful) {
    //     // 支付成功
    //     ToastUtils.showSimpleDialog(
    //         context,
    //         title: '提示',
    //         content: '套餐购买成功',
    //         confirmTitle: '好的',
    //         confirmCallback: () {
    //           // 关闭当前页面
    //           context.pop();
    //         }
    //     );
    //   } else {
    //     // 支付失败
    //     ToastUtils.showToast('支付失败');
    //   }
    // });
    wxpayUtils.registerWechatResp((resp) {
      if (resp is WechatLaunchMiniProgramResp) {
        XLogger.info(
            '拉起小程序: ${resp.errorCode} ${resp.errorMsg}, isSuccessful: ${resp.isSuccessful}');
        XLogger.info('拉起小程序 exMsg: ${resp.extMsg}');
        if (resp.isSuccessful) {
          // 支付成功
          ToastUtils.showSimpleDialog(context,
              title: '提示',
              content: '购买成功',
              confirmTitle: '好的', confirmCallback: () {
            // 关闭当前页面
            context.pop();
          });
        } else {
          // 支付失败
          ToastUtils.showToast('支付失败');
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    alipayUtils.dispose();
    wxpayUtils.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '充值',
          style: TextStyle(color: Colors.black),
        ),
        centerTitle: true,
        backgroundColor: ColorUtils.hexToColor('#f5f5f5'),
        foregroundColor: Colors.white,
      ),
      backgroundColor: ColorUtils.hexToColor('#f5f5f5'),
      body: showLoading ? _showLoading() : _buildBodyView(),
    );
  }
}
